"""hosting"""

import os
from src.core import Enums
from src.api.origin import *
from src.schema import Schema
from flask import request, Response
from src.utils.deep import get_os_info
from src.apps.hosting.manager import info_
from flask_jwt_extended import jwt_required
from src.apps.hosting.manager import Java, Static
# from src.apps.hosting.manager.realog_ import log_sse, stop_log_sse
from src.api.origin import admin_permission, basic_decorator, clear_temp


# 数据传递==================================================================================
# @capture_exception
# @jwt_required()
# @admin_permission
# @refresh_token_on_request
@basic_decorator(multi_nodes=True)
def receive_file(user):
    """接收文件并返回保存路径"""
    file = request.files.get("file")
    if file.content_type is None:
        return {"error": "未上传文件！"}, 400
    time_dir_name = get_os_info().local_time("continuous")
    save_path_dir = CONF.PATH.TEMP + time_dir_name + "/"
    return_path = CONF.PATH.STR.TEMP + time_dir_name + "/" + file.filename
    if not os.path.exists(save_path_dir):
        os.makedirs(save_path_dir)
    save_path = save_path_dir + file.filename
    file.save(save_path)
    return SUCCESS_CODE_CUSTOMIZE({"path": return_path, "time_dir": time_dir_name}, 200)


# 执行操作==================================================================================
@clear_temp
@basic_decorator(hosting=True, multi_nodes=True)
def register(user, stype):
    """注册新服务"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.register_java(**request.get_json(force=True))
            return Java.register(schema, user)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.register_static(**request.get_json(force=True))
            return Static.register(schema, user)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@clear_temp
@basic_decorator(hosting=True, multi_nodes=True)
def deploy(user, stype):
    """部署服务"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.deploy_java(**request.get_json(force=True))
            return Java.deploy(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.deploy_static(**request.get_json(force=True))
            return Static.deploy(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


# @basic_decorator(hosting=True)
# def record(user, stype):
#     """记录"""
#     match stype:
#         case Enums.Hosting.Stypes.JAVA:
#             schema = Schema.record_java(**request.get_json(force=True))
#             return Java.record(schema)
#         case Enums.Hosting.Stypes.STATIC:
#             schema = Schema.record_static(**request.get_json(force=True))
#             return Static.record(schema)
#         case _:
#             return ERROR_CODE.STYPE_ERROR()


@clear_temp
@basic_decorator(hosting=True)
def control(user, stype):
    """控制服务"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.control_java(**request.get_json(force=True))
            return Java.control(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.control_static(**request.get_json(force=True))
            return Static.control(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@clear_temp
@basic_decorator(hosting=True, multi_nodes=True)
def remove(user, stype):
    """删除app"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.remove_java(**request.get_json(force=True))
            return Java.remove(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.remove_static(**request.get_json(force=True))
            return Static.remove(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


# @clear_temp
# @basic_decorator(hosting=True)
# def config(user, stype):
#     """配置"""
#     match stype:
#         case Enums.Hosting.Stypes.JAVA:
#             schema = Schema.config_java(**request.get_json(force=True))
#             return Java.config(schema)
#         case Enums.Hosting.Stypes.STATIC:
#             schema = Schema.config_static(**request.get_json(force=True))
#             return Static.config(schema)
#         case _:
#             return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, multi_nodes=True, result=False)
def info(user, stype):
    """app信息"""
    schema = Schema.info(**request.get_json(force=True))
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            return Java.info(schema, user)
        case Enums.Hosting.Stypes.STATIC:
            return Static.info(schema, user)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, multi_nodes=True)
def rollback(user, stype):
    """回滚"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.rollback_java(**request.get_json(force=True))
            return Java.rollback(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.rollback_static(**request.get_json(force=True))
            return Static.rollback(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, multi_nodes=True)
def migrate(user, stype):
    """迁移"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.migrate_java(**request.get_json(force=True))
            return Java.migrate(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.migrate_web(**request.get_json(force=True))
            return Static.migrate(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


# 信息获取==================================================================================
@basic_decorator(hosting=True, multi_nodes=True, result=False)
def realog(user, stype):
    """实时日志"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.realog(**request.get_json(force=True))
            return Java.realog(schema)
        case Enums.Hosting.Stypes.STATIC:
            return ERROR_CODE.STYPE_NOT_CAPACITY()
        case _:
            return ERROR_CODE.STYPE_ERROR()


# @capture_exception
# @jwt_required()
# @admin_permission
# # @refresh_token_on_request
# def stop_realog(user,):
#     """停止实时日志"""
#     schema = Schema.realog(**request.get_json(force=True))
#     return stop_log_sse(schema)


@basic_decorator(multi_nodes=True, result=False)
def all_apps(user, ):
    """所有应用"""
    return SUCCESS_CODE_CUSTOMIZE(info_.all_apps(user, ), 200)


@basic_decorator()
def all_stypes(user):
    """所有应用类型"""
    result = []
    for i in HOSTING.BASIC.STYPE_LIST:
        if getattr(sof, i.lower()):
            temp = {
                'name': i,
                'status': 'enable',
                'reason': ''
            }
        else:
            temp = {
                'name': i,
                'status': 'disable',
                'reason': ''
            }
        result.append(temp)
    return SUCCESS_CODE.DATA_FETCHED(result)


# @capture_exception
# @jwt_required()
# @admin_permission
# # @refresh_token_on_request
# def all_apps_status(user):
#     """所有app的状态sse"""
#     return Response(info_.all_apps_status(), content_type="text/event-stream")


@basic_decorator(hosting=True, multi_nodes=True)
def remove_record(user, stype):
    """删除记录"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.remove_java_record(**request.get_json(force=True))
            return Java.backup_remove(schema)
        case Enums.Hosting.Stypes.STATIC:
            schema = Schema.remove_static_record(**request.get_json(force=True))
            return Static.backup_remove(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


# @basic_decorator(hosting=True)
# def histlog(user, stype):
#     """历史日志"""
#     match stype:
#         case Enums.Hosting.Stypes.JAVA:
#             schema = Schema.histlog(**request.get_json(force=True))
#             return Java.histlog(schema)
#         case Enums.Hosting.Stypes.STATIC:
#             return ERROR_CODE.STYPE_NOT_CAPACITY()
#         case _:
#             return ERROR_CODE.STYPE_ERROR()


# @basic_decorator(hosting=True)
# def histlog_list(user, stype):
#     """历史日志列表"""
#     match stype:
#         case Enums.Hosting.Stypes.JAVA:
#             schema = Schema.histlog_list(**request.get_json(force=True))
#             return Java.histlog_list(schema)
#         case Enums.Hosting.Stypes.STATIC:
#             return ERROR_CODE.STYPE_NOT_CAPACITY()
#         case _:
#             return ERROR_CODE.STYPE_ERROR()


# @basic_decorator(hosting=True)
# def histlog_list(user, stype):
#     """历史日志列表"""
#     match stype:
#         case Enums.Hosting.Stypes.JAVA:
#             schema = Schema.histlog_num(**request.get_json(force=True))
#             return Java.histlog_num(schema)
#         case Enums.Hosting.Stypes.STATIC:
#             return ERROR_CODE.STYPE_NOT_CAPACITY()
#         case _:
#             return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, result=False, multi_nodes=True)
def look_file_content(user, stype):
    """查看jar文件的内容"""
    schema = Schema.look_file_content(**request.get_json(force=True))
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            return Java.jar_editor(schema)
        case Enums.Hosting.Stypes.STATIC:
            return Static.static_editor(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, result=False, multi_nodes=True)
def file_change(user, stype):
    """修改jar文件的内容"""
    schema = Schema.file_change(**request.get_json(force=True))
    match stype:
        case Enums.Hosting.Stypes.JAVA: 
            return Java.jar_change(schema)
        case Enums.Hosting.Stypes.STATIC:
            return Static.static_change(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@basic_decorator(hosting=True, multi_nodes=True, process_record=False)
def download_file(user, stype):
    """下载文件"""
    match stype:
        case Enums.Hosting.Stypes.JAVA:
            schema = Schema.file_download(**{"app_id": request.args.get("app_id")})
            return Java.jar_download(schema)
        case Enums.Hosting.Stypes.STATIC:
            return Static.static_download(schema)
        case _:
            return ERROR_CODE.STYPE_ERROR()


@basic_decorator(result=False, multi_nodes=True)
def fm_nginx_template_conf(user):
    """获取nginx配置模板"""
    from src.apps.hosting.manager.info_ import fm_nginx_template_conf
    return SUCCESS_CODE_CUSTOMIZE(fm_nginx_template_conf())


@basic_decorator(result=False, multi_nodes=True)
def count(user):
    """获取应用数量"""
    from src.apps.hosting.basic_info import all_count
    return all_count()


@basic_decorator(result=False, multi_nodes=True)
def check_choose_file(user):
    """判断选中文件是否合法"""
    Schema.check_choose_file(**request.get_json(force=True))
    return SUCCESS_CODE.CHOOSE_FILE_OK()